package com.cn.wanxi.servlet.user;

import com.alibaba.fastjson.JSONObject;
import com.cn.wanxi.model.ResultModel;
import com.cn.wanxi.model.UserModel;
import com.cn.wanxi.service.UserService;
import com.cn.wanxi.service.impl.UserServiceImpl;
import com.cn.wanxi.util.Tool;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/back/user/add")//前端访问后台的地址
public class UserAddServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        0.乱码处理
//        请求，响应
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");

//        1.得到前端的数据
        String username = req.getParameter("username");
        String birthday = req.getParameter("birthday");
        String password = req.getParameter("password");
        String phone = req.getParameter("phone");
        String email = req.getParameter("email");
        String hobby = req.getParameter("hobby");
        String enable = req.getParameter("enable");
        String sex = req.getParameter("sex");
//        2.对前端的数据进行封装成对象
        UserModel userModel = new UserModel();
        userModel.setUsername(username);
        userModel.setBirthday(birthday);
        userModel.setPassword(Tool.EncoderByMd5(password));
        userModel.setPhone(phone);
        userModel.setEnable(Tool.strToInt(enable));
        userModel.setEmail(email);
        userModel.setHobby(hobby);
        userModel.setSex(sex);

//        3.调用服务逻辑层
        UserService userService = new UserServiceImpl();
//        4.得到返回数据
        ResultModel resultModel = userService.add(userModel);
//        5.返回给前端
        resp.getWriter().println(JSONObject.toJSONString(resultModel));
    }
}
